import React from 'react'
import {withRouter} from 'react-router'
import BaseComponent from 'basecomponent'
import classNames from 'classnames'
import icons from 'icons'
import Button from "button";
import Dropzone from 'react-dropzone';
import './style.scss'
import {Form, Select, Checkbox} from 'antd';
import api from 'apis'
import AntTable from 'anttable'
import appConfig from 'config'
import {USER_KEY} from 'auth'
import store from 'store'
import {handleState} from 'utils/staticType'
const FormItem = Form.Item
class ReviseCompany extends BaseComponent {
  constructor() {
    super(...arguments);
    const location = this.props.location;
    this.state = {
      universityData: {
        Id: location.query.Id ?  parseInt(location.query.Id): -1,
        Addr: -1,
        Tags: '',
        DetailHtml: '',
        DetailFiles: '',
        Introduce:'',
        Pics: '',
        PicsTags: '',
        Image: '',
        Name: '',
        TotalPlayTimes: -1,
        Timestamp: 0,
        Web: '',
      },
      universityLogoImg: '',
      universityLogoPreview: '',
      showCheckbox: false,
      sightsData: [],
      checkSightsIndex: [],
      currentPage: 1,
      pageSize: 5,
      provinceData: [],
      cityData: [],
      collegeData: [],
      addCollegeCode: 0,//0:本科 1:硕士
    }
    store.set('currentUId', location.query.Id ? location.query.Id : 1)
  }

  componentDidMount() {
    const {universityData} = this.state;
    if (this.checkUniversityId(universityData)) {
      this.getUniversityDetail(universityData.Id)
      this.getCollegeList(universityData.Id);
    } else {
      this.getProvinceInfo();
    }
  }

  getUniversityDetail(id) {
    let uid = id ? id : store.get('currentUId')
    this.getUDetailRP = api.university.getUniversityDetail(uid);
    this.registerRequest(this.getUDetailRP.request);
    this.getUDetailRP.promise
      .then((res) => {
        res.Data && this.setState({universityData: res.Data});
        res.Data && this.mapUniversityData(res.Data);
      })
  }

  getCollegeList(id) {
    let uid = id ? id : store.get('currentUId')
    this.getCListRP && this.getCListRP.request.abort();
    this.getCListRP = api.university.getCollegeList(uid);
    this.registerRequest(this.getCListRP.request);
    this.getCListRP.promise
      .then((res) => {
        res.Data && this.setState({collegeData: res.Data});
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  addCollege() {
    const {universityData, collegeName, collegeIntro, collegeData} = this.state
    let postData = {
      UniversityId: universityData.Id,
      Name: collegeName,
      Introduce: collegeIntro
    }
    this.addCollegeRP && this.addCollegeRP.request.abort();
    this.addCollegeRP = api.university.addCollege(postData);
    this.registerRequest(this.addCollegeRP.request);
    this.addCollegeRP.promise
      .then((res) => {
        if (res.Data) {
          collegeData.push(res.Data)
          this.setState({collegeData: collegeData})
        }
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  topCollege(text, record) {
    let collegeData = {}
    if(record.Order && record.Order === 1){
      collegeData = Object.assign({}, record, {Order: 0})
    }else{
      collegeData = Object.assign({}, record, {Order: 1})
    }
    this.reviseCollegeRP && this.reviseCollegeRP.request.abort()
    this.reviseCollegeRP = api.university.reviseCollege(collegeData.Id, collegeData)
    this.registerRequest(this.reviseCollegeRP.request)
    this.reviseCollegeRP.promise
      .then((res) => {
        alert('成功')
        this.getCollegeList(this.state.universityData.Id)
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  watchCollege(text, record) {
    this.props.router.push({
      pathname: 'home/revise/college',
      query: {Id: record.Id},
      state: {
        revise: false,
      }
    });
  }

  mapUniversityData(detail) {
    let tags = detail.Tags.split('|')
    this.props.form.setFieldsValue({
      Name: detail.Name,
      Introduce: detail.Introduce,
      levelF:tags[0] ? tags[0]:'',
      batch:tags[1] ? tags[1]:'',
      category:tags[3] ? tags[3]:'',
    });
    this.getProvinceInfo(parseInt(detail.Addr / 1000) * 1000, detail.Addr);
    this.setState({
      universityLogoImg: `${appConfig.apiHost}/File/?pid=${detail.Image}&key=${store.get(USER_KEY)}`,
      sightsData: detail.Pics ? detail.Pics.split('|').map((i) => {
        return {pic: i}
      }) : [],
    })
  }

  getProvinceInfo(Pid, Cid) {
    this.getProviceRP = api.address.getProvince();
    this.registerRequest(this.getProviceRP.request);
    this.getProviceRP.promise
      .then((res) => {
        res.Data && this.setState({provinceData: res.Data});
        Cid && this.getCityInfo(Pid, Cid);
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  getCityInfo(Pid, Cid) {
    this.getCityRP && this.getCityRP.request.abort();
    this.getCityRP = api.address.getCity(Pid);
    this.registerRequest(this.getCityRP.request);
    this.getCityRP.promise
      .then((res) => {
        res.Data && this.setState({cityData: res.Data});
        res.Data && this.props.form.setFieldsValue({
          AddrP: Pid.toString(),
          AddrC: Cid.toString(),
        })
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  handleProvinceSelect(value, option) {
    if (value) {
      this.getCityRP && this.getCityRP.request.abort();
      this.getCityRP = api.address.getCity(value);
      this.registerRequest(this.getCityRP.request);
      this.getCityRP.promise
        .then((res) => {
          res.Data && this.setState({cityData: res.Data, defaultProvince: value});
          res.Data && this.props.form.setFieldsValue({
            AddrC: res.Data[0].Id.toString()
          })
        })
        .catch((err) => {
          alert(err.msg)
        })
    }

  }

  handleLogoFileSelect(files) {
    const {universityData} = this.state
    let file = files[0];
    if (file) {
      this.uploadLogoRP && this.uploadLogoRP.request.abort();
      this.uploadLogoRP = api.file.uploadFile(file);
      this.registerRequest(this.uploadLogoRP.request);
      this.uploadLogoRP.promise
        .then((res) => {
          handleState(res.State)
          this.setState({
            universityLogoImg: res.Data || '', universityData: Object.assign({},
              universityData, {Image: res.Data || ''})
          });
        })
        .catch((err) => {
          alert(err.msg)
        })
    }
  }

  handleSightsFileSelect(files) {
    let file = files[0];
    let list = this.state.sightsData || [];
    if (file) {
      list.push(file);
      this.setState({sightsData: list});
    }
  }

  uploadSightsFiles(i) {
    const {sightsData} = this.state;
    let index = i;
    if (index > -1) {
      let postData = sightsData[index];
      if (postData instanceof File) {
        this.uploadRP && this.uploadRP.request.abort();
        this.uploadRP = api.file.uploadFile(postData);
        this.registerRequest(this.uploadRP.request);
        this.uploadRP.promise
          .then((res) => {
            sightsData[index] = {pic: res.Data}
            this.setState({sightsData: sightsData}, () => {
              if (index < sightsData.length) {
                this.uploadSightsFiles(index + 1);
              } else {
                this.uploadSightsFiles(-1);
              }
            })
          })
          .catch((err) => {
            if (index < sightsData.length) {
              this.uploadSightsFiles(index + 1);
            } else {
              this.uploadSightsFiles(-1);
            }
          })
      } else {
        if (index < sightsData.length) {
          this.uploadSightsFiles(index + 1);
        } else {
          this.uploadSightsFiles(-1);
        }
      }
    } else {
      this.uploadUniversityData()
    }
  }

  uploadUniversityData() {
    const {universityData, sightsData} = this.state;
    let picStr = ''
    sightsData.length > 0 && sightsData.forEach(function (item, index) {
      if (index === 0 || index === sightsData.length) {
        picStr = picStr + item.pic
      } else {
        picStr = picStr + '|' + item.pic
      }
    });
    universityData.Pics = picStr
    if (this.checkUniversityId(universityData)) {
      this.addUniversityRP && this.addUniversityRP.request.abort();
      this.addUniversityRP = api.university.reviseUniversity(universityData.Id, universityData);
      this.registerRequest(this.addUniversityRP.request);
      this.addUniversityRP.promise
        .then((res) => {
          res.Data && this.setState({universityData: res.Data});
          alert('保存成功')
        })
        .catch((err) => {
          alert(err.msg)
        })
    } else {
      alert('请填写基本信息')
    }
  }

  handleSubmit(e) {
    e.preventDefault();
    const{provinceData,universityData} = this.state
    this.props.form.validateFields((err, values) => {
      if (!err) {
        universityData.Name = values.Name;
        universityData.Addr = values.AddrC;
        universityData.Introduce = values.Introduce;
        universityData.TotalPlayTimes = values.TotalPlayTimes;
        let addr = ''
        provinceData.map((item)=>{
          if(values.AddrP && parseInt(values.AddrP) === item.Id){
            addr = item.Name
          }
        })
        universityData.Tags = `${values.levelF ? values.levelF : ''}|${values.batch ? values.batch : ''}|${addr}|${values.category ? values.category : ''}`
        if (this.checkUniversityId(universityData)) {
          this.reviseUniversityRP && this.reviseUniversityRP.request.abort();
          this.reviseUniversityRP = api.reviseUniversityRP.reviseUniversity(universityData.Id, universityData);
          this.registerRequest(this.reviseUniversityRP.request);
          this.reviseUniversityRP.promise
            .then((res) => {
              res.Data && this.setState({universityData: res.Data});
              handleState(res.State)
            })
            .catch((err) => {
              alert(err.msg)
            })
        } else {
          delete universityData.Id
          this.addUniversityRP && this.addUniversityRP.request.abort();
          this.addUniversityRP = api.university.addUniversity(universityData);
          this.registerRequest(this.addUniversityRP.request);
          this.addUniversityRP.promise
            .then((res) => {
              res.Data && this.setState({universityData: res.Data});
              handleState(res.State)
            })
            .catch((err) => {
              alert(err.msg)
            })
        }
      }
    });
  }

  getLogoImgDiv() {
    const {universityLogoImg, universityLogoPreview} = this.state
    if (universityLogoPreview.length > 0) {
      return <img className={'preview-img'} src={universityLogoPreview}/>
    } else {
      if (universityLogoImg.length > 0) {
        return <img className={'preview-img'}
                    src={`${appConfig.apiHost}/File/?pid=${universityLogoImg}&key=${store.get(USER_KEY)}`}/>
      } else {
        return <div className={'default-wrapper'}>
          <img className={'image-default'} src={icons.uploadImg}/>
          <span>点击添加LOGO</span>
        </div>
      }
    }
  }

  checkUniversityId(universityData){
    return !(universityData.Id === -1 || universityData.Id === '-1' ||typeof universityData.Id === 'undefined')
  }

  render() {
    const {wrapperName, buttonWrapperName, clickBack, children} = this.props;
    const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form;
    const {
      universityData, sightsData, currentPage, pageSize, showCheckbox, provinceData, cityData, collegeData
    } = this.state;

    const columns = [{
      title: '编号',
      dataIndex: 'Id',
      key: 'Id',
    }, {
      title: '学院名称',
      dataIndex: 'Name',
      key: 'Name'
    },
      {
        title: '时长',
        dataIndex: 'TotalDuration',
        key: 'TotalDuration'
      },
      {
        title: '上传时间',
        dataIndex: 'uploadTime',
        key: 'uploadTime',
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
             <a onClick={() => {
               this.topCollege(text, record)
             }}>{record.Order && record.Order === 1 ? '取消置顶' : '置顶'}</a>
            <span className="ant-divider"/>
          <a onClick={() => {
            this.watchCollege(text, record)
          }}>查看</a>
        </span>
        ),
      }];

    const hoverContent = (
      <div className={'hover-wrapper'} style={
        {
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          width: '100%'
        }
      }>
        <Button className={'benke-btn'} style={{
          width: '80%',
          border: 'none',
          backgroundColor: '#ff595f',
          margin: 'auto',
          marginBottom: '8px'
        }} onClick={() => {
          if (this.checkUniversityId(universityData)) {
            this.props.router.replace({
              pathname: '/home/add/college',
              query: {id: -1, category: 0},
              state: {uid: universityData.Id}
            })
          } else {
            alert('请先添加学校')
          }
        }}>本科学院</Button>
        <Button className={'shuoshi-btn'} style={{
          width: '80%',
          border: 'none',
          backgroundColor: '#ff595f',
          margin: 'auto',
          marginTop: '0'
        }} onClick={() => {
          if (this.checkUniversityId(universityData)) {
            this.props.router.replace({
              pathname: '/home/add/college',
              query: {id: -1, category: 1},
              state: {uid: universityData.Id}
            })
          } else {
            alert('请先添加学校')
          }
        }}>硕士学院</Button>
      </div>
    )

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
      }),
    };
    const self = this;
    return (
      <div className={'sem-main-content'}>
        <div className={classNames('company-wrapper', wrapperName)}>
          <div className={classNames('button-wrapper', buttonWrapperName)}>
            <Button className={'back-button'} onClick={() => {
              this.props.router.goBack()
            }}>{Button.AddOn({
              src: icons.backIcon, style: {
                width: '1rem',
                height: '1rem',
                display: 'block',
                backgroundRepeat: 'no-repeat',
              }
            })}</Button>
            <div className={'add-name'}>
              添加学校
            </div>
          </div>
          <Form onSubmit={this.handleSubmit.bind(this)} hideRequiredMark={true}>

            <div className={'body-top'}>
              <Dropzone className={'image-drop-zone'}
                        onDrop={this.handleLogoFileSelect.bind(this)}
                        accept={'image/*'}
                        multiple={false}>
                {this.getLogoImgDiv()}
              </Dropzone>
              <div className={'body-top-middle'}>
                <div className={'option-wrapper'}>
                  <div className={'option-title'}>学校名称</div>
                  <FormItem>
                    {getFieldDecorator('Name', {initialValue: universityData.Name})(
                      <input className={'option-input'}
                             type={'text'}/>
                    )}
                  </FormItem>
                </div>
                <div className={'option-wrapper'}>
                  <div className={'option-title'}>学校地址</div>
                  <FormItem>
                    {getFieldDecorator('AddrP')(
                      <Select className={'province-select select-margin'}
                              onSelect={this.handleProvinceSelect.bind(this)}
                              notFoundContent={'-'}>
                        {provinceData.map(function (item, index) {
                          return <Option key={item.Id.toString()} value={item.Id.toString()}>{item.Name}</Option>
                        })}
                      </Select>
                    )
                    }
                  </FormItem>
                  <FormItem>
                    {getFieldDecorator('AddrC')(
                      <Select className={'city-select'}
                              notFoundContent={'-'}
                      >
                        {
                          cityData && cityData.map(function (item, index) {
                            return <Option key={item.Id.toString()} value={item.Id.toString()}>{item.Name}</Option>
                          })
                        }
                      </Select>
                    )
                    }
                  </FormItem>
                </div>
                <div className={'option-wrapper'} style={{marginBottom: '0'}}>
                  <div className={'option-title'}>播放次数</div>
                  <FormItem>{
                    getFieldDecorator('TotalPlayTimes', {initialValue: universityData.TotalPlayTimes})(
                      <input className={'option-input'} type={'number'}/>
                    )
                  }</FormItem>
                </div>
              </div>
              <div className={'body-top-end'}>
                <div className={'option-wrapper'}>
                  <div className={'option-title'}>学校级别</div>
                  <FormItem>{
                    getFieldDecorator('levelF')(
                      <Select className={'level-first-select big'}>
                        <Option value={'双一流'}>双一流</Option>
                        <Option value={'985'}>985</Option>
                        <Option value={'211'}>211</Option>
                      </Select>
                    )
                  }
                  </FormItem>
                </div>
                <div className={'option-wrapper'}>
                  <div className={'option-title'}>学校批次</div>
                  <FormItem>{
                    getFieldDecorator('batch')(
                      <Select className={'batch-select big'}>
                        <Option value={'本科'}>本科</Option>
                        <Option value={'专科'}>专科</Option>
                      </Select>
                    )
                  }
                  </FormItem>
                </div>
                <div className={'option-wrapper'} style={{marginBottom: '0'}}>
                  <div className={'option-title'}>学校类别</div>
                  <FormItem>{
                    getFieldDecorator('category')(
                      <Select className={'category-select big'}>
                        <Option value={'综合'}>综合</Option>
                        <Option value={'工科'}>工科</Option>
                        <Option value={'医学'}>医学</Option>
                        <Option value={'农业'}>农业</Option>
                        <Option value={'体育'}>体育</Option>
                      </Select>
                    )
                  }</FormItem>
                </div>
              </div>
            </div>

            <div className={'body-middle'}>
              <div className={'title-wrapper'}>
                <span className={'title-bar'}/>
                <span className={'title-text'}>学校简介</span>
                <Button className={'title-btn-save'} buttonType={'submit'} onClick={() => {
                }}>保存</Button>
              </div>
              <FormItem>{
                getFieldDecorator('Introduce', {initialValue: universityData.Introduce})(
                  <textarea className={'company-intro'}/>
                )
              }</FormItem>
              <div className={'title-wrapper'}>
                <span className={'title-bar'}/>
                <span className={'title-text'}>学校风景</span>
                <Button className={'title-btn-more'} buttonType={"button"} onClick={() => {
                  if (sightsData && sightsData.length > 0) {
                    this.setState({showCheckbox: !showCheckbox});
                  }
                }}>更多</Button>
                <Button className={'title-btn-save'}
                        buttonType={'button'}
                        onClick={() => {

                          if (showCheckbox) {
                            let data = [];
                            sightsData.map(function (item, index) {
                              if (!item.checked)
                                return data.push(item);
                            });
                            if (data.length === 0) {
                              this.setState({showCheckbox: false, sightsData: data});
                            } else {
                              this.setState({sightsData: data});
                            }
                          } else {
                            this.uploadSightsFiles(0);
                          }
                        }}>{showCheckbox ? '删除' : '保存'}</Button>
              </div>
              <div className={'sights-wrapper'}>
                <ul className={'sights-ul'}>
                  {
                    sightsData && sightsData.map(function (item, index) {
                      return <li className={'sights-li'}>
                        {showCheckbox && <Checkbox className={'sights-check-box'} value={index} checked={item.checked}
                                                   onChange={(e) => {
                                                     let index = parseInt(e.target.value);
                                                     let data = sightsData.map(function (i, d) {
                                                       return d === index ? Object.assign(i, {checked: e.target.checked}) : i;
                                                     });
                                                     self.setState({sightsData: Object.assign(sightsData, data)});
                                                   }
                                                   }/>}
                        <img className={'sights-img'} src={typeof item.pic === 'string' ?
                          `${appConfig.apiHost}/File/?pid=${item.pic}&key=${store.get(USER_KEY)}` :
                          item.preview} alt={'Opps!'}/>
                      </li>
                    })
                  }
                </ul>
                <Dropzone className={'image-drop-zone'}
                          onDrop={this.handleSightsFileSelect.bind(this)}
                          action={'http://101.201.51.208:9528/File'}
                          accept={'image/*'}
                          multiple={false}>
                  <div className={'default-wrapper'}>
                    <img className={'image-default'} src={icons.uploadImg}/>
                    <span>点击添加图片</span>
                  </div>
                </Dropzone>
              </div>
            </div>
          </Form>

          <div className={'body-end'} style={{height: '25rem'}}>
            <div className={'title-wrapper'}>
              <span className={'title-bar'}/>
              <span className={'title-text'}>招生学院</span>
              {/*<Popover trigger={'hover'} title={'添加'} content={hoverContent}>*/}
                <Button className={'title-btn-more'} onClick={() => {
                  if (this.checkUniversityId(universityData)) {
                    this.props.router.replace({
                      pathname: '/home/add/college',
                      query: {Id: -1},
                      state: {uid: universityData.Id}
                    })
                  } else {
                    alert('请先添加学校')
                  }
                }}>添加</Button>
              {/*</Popover>*/}
              <Button className={'title-btn-save'} onClick={() => {
              }}>删除</Button>
            </div>
            <AntTable columns={columns} data={collegeData} rowSelection={rowSelection}
                      pagination={true} currentPage={currentPage} pageSize={pageSize}
                      onChange={(pagination) => {
                        this.setState({
                          currentPage: pagination.current,
                          pageSize: pagination.pageSize,
                        })
                      }}
            />
          </div>
        </div>
      </div>
    );
  }
}

module.exports = Form.create()(withRouter(ReviseCompany));
